#pragma once

#include <iostream>
#include <string>
#include <vector>
#include <jsoncpp/json/json.h>

#include "../common/log.hpp"
#include "../common/util.hpp"
#include "../common/httplib.h"
// #include "./oj_model.hpp"
#include"./oj_model2.hpp"

#include "./oj_view.hpp"

namespace ns_control
{
    using namespace ns_log;
    using namespace ns_util;
    using namespace ns_model;
    using namespace std;
    using namespace ns_view;

    // 提供服务的主机
    class Machine
    {
    public:
        std::string ip;   // 编译服务的ip
        std::string port; // 编译服务的port
        uint64_t load;    // 编译服务的负载
        std::mutex *mux;  // mutex禁止拷贝 使用指针
    public:
        Machine() : ip(""), port(""), load(0), mux(nullptr)
        {
        }
        ~Machine()
        {
        }

    public:
        // 提升主机负载
        void IncLoad()
        {
            if (mux)
                mux->lock();
            ++load;
            mux->unlock();
        }
        // 减小主机负载
        void DecLoad()
        {
            if (mux)
                mux->lock();
            --load;
            mux->unlock();
        }
        //清空主机负载
        void ReserLoad()
        {
            if (mux)
                mux->lock();
            load = 0;
             mux->unlock();
        }
        // 获得主机负载
        uint64_t Load()
        {
            uint64_t retload = 0;
            if (mux)
                mux->lock();
            retload = load;
            mux->unlock();
            return retload;
        }
    };

    const std::string server_machine_path = "./conf/server_machine.conf";
    // 负载均衡
    class LoadBlance
    {
    private:
        // 提供编译服务的所有主机 下标就是每个主机的id
        std::vector<Machine> machines;
        // 在线主机id
        std::vector<int> online;
        // 离线主机id
        std::vector<int> offline;
        std::mutex mux;

    public:
        LoadBlance()
        {
            assert(LoadConf(server_machine_path));
            LOG(INFO) << "加载配置文件" << server_machine_path << "成功!" << std::endl;
        }
        ~LoadBlance()
        {
        }

    public:
        // 加载配置文件
        bool LoadConf(const std::string &machine_conf)
        {
            std::ifstream in(machine_conf);
            if (!in.is_open())
            {
                LOG(FATAL) << "打开配置文件失败 :" << machine_conf << std::endl;
                return false;
            }
            std::string line;
            while (getline(in, line))
            {
                std::vector<std::string> tokens;
                stringutil::splitstring(line, &tokens, ":");
                if (tokens.size() != 2)
                {
                    LOG(WARNING) << "配置文件格式出错!" << std::endl;
                    continue;
                }
                Machine mach;
                mach.ip = tokens[0];
                mach.port = tokens[1];
                mach.load = 0;
                mach.mux = new mutex();

                online.push_back(machines.size());
                machines.push_back(mach);
            }
            in.close();
            return true;
        }

        // 选择负载最小的主机
        bool SmartChoice(int *d, Machine **m)
        {
            // 找到负载最小的主机
            mux.lock();
            if (online.size() == 0)
            {
                mux.unlock();
                LOG(FATAL) << "没有在线主机!!!" << std::endl;
                return false;
            }
            uint64_t min_load = 0;
            *d = online[0];
            *m = &machines[online[0]];
            for (int i = 0; i < online.size(); i++)
            {
                if (min_load > machines[online[i]].Load())
                {
                    min_load = machines[online[i]].Load();
                    *d = online[i];
                    *m = &machines[online[i]];
                }
            }
            mux.unlock();

            return true;
        }
        //当所有主机都下线时，统一上线所有主机
        void OnlineMachine()
        {
            mux.lock();
            online.insert(online.end(),offline.begin(),offline.end());
            offline.erase(offline.begin(),offline.end());
            mux.unlock();
        }

        //下线主机
        void OfflineMachine(int &id)
        {
            mux.lock();
            for (auto iter = online.begin(); iter != online.end(); iter++)
            {
                if (*iter == id)
                {
                    machines[id].ReserLoad();//将要离线的主机负载清零
                    iter = online.erase(iter);
                    offline.push_back(id);
                    break; // break的存在让我们不必担心迭代器失效的问题
                }
            }
            mux.unlock();
        }
        
        // for test
        void ShowMachines()
        {
            mux.lock();
            std::cout << "当前在线主机列表: ";
            for (auto &id : online)
            {
                std::cout << id << " ";
            }
            std::cout << std::endl;
            std::cout << "当前离线主机列表: ";
            for (auto &id : offline)
            {
                std::cout << id << " ";
            }
            std::cout << std::endl;
            mux.unlock();
        }
    };

    class control
    {
    private:
        Model _model;            // 进行数据交互
        View _view;              // 网页渲染
        LoadBlance _load_blance; // 负载均衡

    public:
        control()
        {
        }
        ~control()
        {
        }

    public:
        //恢复所有主机 让它们都上线
        void RecoveryMachine()
        {
            _load_blance.OnlineMachine();
        }
        // 获取所有题目列表
        bool allquestion(std::string *html)
        {
            bool ret = true;
            vector<Question> allq;
            if (_model.GetAllQuestions(&allq))
            {
                // 将数据转换成网页返回
                sort(allq.begin(),allq.end(),[](const Question &q1,const Question &q2){
                    return atoi(q1.number.c_str()) < atoi(q2.number.c_str());
                });
                _view.AllExpandHtml(allq, html);
            }
            else
            {
                (*html) = "获取题目列表失败";
                ret = false;
            }
            return ret;
        }
        // 获取单个题目详细信息
        bool onequestion(const std::string &number, std::string *html)
        {
            bool ret = true;
            Question q;
            if (_model.GetOneQuestion(number, &q))
            {
                // 将数据转换成网页返回
                _view.OneExpandHtml(q, html);
            }
            else
            {
                (*html) = number + "题目不存在!";
                ret = false;
            }
            return ret;
        }

        // 提交代码 判断对错
        //  参数：
        //  in_json: {"code": "#include...", "input": "","cpu_limit":1, "mem_limit":10240}
        //  out_json: {"status":"0", "reason":"","stdout":"","stderr":"",}
        void Judge(const std::string &number, const std::string &in_json, std::string *out_json)
        {
            // 0. 根据题目编号，直接拿到对应的题目细节
            Question q;
            _model.GetOneQuestion(number, &q);
            // 1. in_json进行反序列化，得到题目的id，得到用户提交源代码code，input
            Json::Value in_value;
            Json::Reader reader;
            reader.parse(in_json, in_value);
            // 2. 重新拼接用户代码+测试用例代码，形成新的代码
            Json::Value compile_value;
            compile_value["code"] = in_value["code"].asString() + q.tail;
            compile_value["input"] = in_value["input"].asString();
            compile_value["cpu_limit"] = q.cpu_limit;
            compile_value["mem_limit"] = q.mem_limit;
            // 将compile_value序列化
            Json::StyledWriter writer;
            std::string compile_json = writer.write(compile_value);
            // 3. 选择负载最低的主机(差错处理)
            while (true)
            {
                int id;
                Machine *m;
                if (!_load_blance.SmartChoice(&id, &m))
                {
                    LOG(FATAL) << "选择主机失败!!!" << std::endl;
                    break;
                }
                LOG(FATAL) << "选择主机成功，id :" << id << "ip：" << m->ip << ",port:" << m->port << std::endl;
                // 4. 然后发起http请求，得到结果
                Client cli(m->ip, atoi(m->port.c_str()));
                m->IncLoad();
                if (auto res = cli.Post("/compile_and_run", compile_json, "application/json;charset=utf-8"))
                {
                    if (res->status == 200)
                    {
                        // 5. 将结果赋值给out_json
                        *out_json = res->body;
                        m->DecLoad();
                        LOG(FATAL) << "请求编译和运行服务成功" << std::endl;
                        break;
                    }
                }
                else
                {
                    // 请求失败
                    LOG(FATAL) << "请求主机失败，id :" << id << "ip：" << m->ip << ",port:" << m->port << std::endl;
                    // 下线该主机
                    _load_blance.OfflineMachine(id);
                    _load_blance.ShowMachines();//用来调试代码
                }
            }
        }
    };
}